package com.wry.cloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <h1> GateWay过滤器 <h1>
 *
 * @author 魏如元
 * @since 2022/9/9
 */
@Component
@Slf4j
public class MyGateWayFilter implements GlobalFilter, Ordered {

    /**
     * 相当于用户登录时校验用户
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("***********come in MyLogGateWayFilter:  {}", LocalDateTime.now());
        String name = exchange.getRequest().getQueryParams().getFirst("uname");
        // 模拟从库中查询用户
        final List<String> nameList = List.of("tom", "jack", "jerry");
        if(!nameList.contains(name)){
            log.info("*******用户名不存在，非法用户，o(╥﹏╥)o");
            exchange.getResponse().setRawStatusCode(HttpStatus.NOT_ACCEPTABLE.value());
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
